<?php

/**
 * Copyright 2008 William J. Szerdy Jr.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * @author Bill Szerdy <bszerdy@gmail.com>
 *
 * 12.05.2008 - bszerdy : Created.
 *
 */

Class Data implements PokerBlind {
    /**
     * Loads the data from the json data file and returns an array
     * containing the entire dataset.
     */
    static function Load_Data() {
        $fh = fopen(DATA_LOCATION, 'r') or die("Can't open file " . DATA_LOCATION);
        $blinds = fread($fh, filesize(DATA_LOCATION));
        fclose($fh);
        $temp = json_decode($blinds);
        $retval = array();
        $i = 0;

        foreach ($temp as $b) {
            $blind = new SingleBlind($b->level, $b->small_blind, $b->big_blind, $b->ante, $b->time);
            $retval[++$i] = $blind;
        }

        return $retval;
    }
    
    /**
     * Saves the dataset returned to the file. $data is assumed to
     * be an array of SingleBlind objects.
     *
     * @param array $data
     * @param bool $backup
     *
     * @todo - find a better way to convert the data to a json_data
     *          dataset.
     */
    static function Save_Data($data, $backup = FALSE) {
        $blinds = array();
        foreach ($data as $blind) {
            $temp = array();
            $temp['level']          = $blind->level;
            $temp['small_blind']    = $blind->small_blind;
            $temp['big_blind']      = $blind->big_blind;
            $temp['ante']           = $blind->ante;
            $temp['time']           = $blind->time;
            array_push($blinds, $temp);
        }

        if ($backup) {
            copy(DATA_LOCATION, DATA_LOCATION . '.bak');
        }

        $fh = fopen(DATA_LOCATION, 'w') or die("Can't open file" . DATA_LOCATION);
        
        fwrite($fh, json_encode($blinds));
        fclose($fh);
    }
}

?>
